import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
// 引入创建的action
import {
  toolkitIncrement,
  toolkitDecrement,
  toolkitAsyncGetUser,
  rtkCreateAsyncThunk // 副作用，异步请求
} from '../../../store/toolKit/toolkitCounterSlice';
import { loadAsyncData } from '../../../store/toolKit/toolkitAsyncThunk';

const MyReduxToolkit = () => {
  const dispatch = useDispatch();
  const toolkitStore = useSelector(state => {
    // console.log('state !!!', state)
    return {
      ...state.toolkitCounterSlice,
      ...state.toolkitAsyncThunk.userList
    };
  });

  useEffect(() => {
    // 手动触发异步请求
    // dispatch(loadAsyncData())
    dispatch(rtkCreateAsyncThunk());
  }, []);

  return (
    <div>
      <h1>Redux Toolkit 工具集 123</h1>
      <p>
        redux 中的全局数据：
        {/* {JSON.stringify(toolkitStore)} */}
        {toolkitStore.title}
        {toolkitStore.count}
      </p>
      <ul style={{ fontSize: '8px' }}>
        {toolkitStore.userList.map((d, i) => (
          <li key={i}>
            {Object.keys(d)} - {Object.values(d)}
          </li>
        ))}
      </ul>
      <button
        onClick={() => {
          // dispatch派发action
          dispatch(toolkitIncrement({ step: 2 }));
        }}
      >
        改变tooltik中的数据 +
      </button>
      <button
        onClick={() => {
          dispatch(toolkitDecrement());
        }}
      >
        数据减去
      </button>
      <button
        onClick={() => {
          // 使用dispatch触发副作用操作（内置thunk）
          dispatch(toolkitAsyncGetUser());
        }}
      >
        获取用户
      </button>
    </div>
  );
};

export default MyReduxToolkit;
